<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkDepartment\Action\Dashboard;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\WorkDepartment\Contract\WorkDepartmentContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeDepartmentContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 组织管理- 查看人员列表.
 *
 * Class GetDepartmentEmployee.
 * @Controller
 */
class GetDepartmentEmployee extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var CorpContract
     */
    protected $corpService;

    /**
     * @Inject
     * @var WorkDepartmentContract
     */
    protected $workDepartmentService;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployeeService;

    /**
     * @Inject
     * @var WorkEmployeeDepartmentContract
     */
    protected $workEmployeeDepartmentService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/workDepartment/getDepartmentEmployee", methods="get")
     * @return array 返回数组
     */
    public function handle(): array
    {
        // 参数验证
        $this->validated($this->request->all());

        $params = [
            'employeeName' => $this->request->input('employeeName', ''),
            'departmentId' => (int) $this->request->input('departmentId'),
            'page' => $this->request->input('page', 1),
            'perPage' => $this->request->input('perPage', 10),
        ];

        $corpId = user()['corpIds'];
        if (count($corpId) > 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '请先选择企业');
        }
        // 组织响应数据
        $data = [
            'page' => [
                'perPage' => $params['perPage'],
                'total' => 0,
                'totalPage' => 0,
            ],
            'list' => [],
        ];

        $currentDepartmentIds = [$params['departmentId']];
        if ($params['departmentId'] == 0) {
            $workDepartments = $this->workDepartmentService->getWorkDepartmentsByCorpId((int) $corpId[0], ['id']);
            if (empty($workDepartments)) {
                return $data;
            }
            $currentDepartmentIds = (array) array_column($workDepartments, 'id');
        } else {
            // 所有部门id
            $currentDepartmentIds = $this->recursion($params['departmentId'], [$params['departmentId']]);
        }

        // 查询部门下所有员工
        $employee = $this->workEmployeeDepartmentService->getWorkEmployeeDepartmentsByDepartmentIds($currentDepartmentIds, ['employee_id']);
        if (empty($employee)) {
            return $data;
        }
        $employeeIds = array_column($employee, 'employeeId');
        // 组织查询条件
        $where['corp_id'] = (int) user()['corpIds'][0];
        $where['status'] = 1;
        $where[] = ['id', 'IN', $employeeIds];
        if (! empty($params['employeeName'])) {
            $where[] = ['name', 'like', '%' . $params['employeeName'] . '%'];
        }
        $options = [
            'page' => $params['page'],
            'perPage' => $params['perPage'],
            'orderByRaw' => 'id desc',
        ];
        $columns = [
            'id',
            'name',
            'wx_user_id',
            'avatar',
            'alias',
            'main_department_id',
        ];
        // 查询数据
        $res = $this->workEmployeeService->getWorkEmployeeList($where, $columns, $options);

        if (empty($res['data'])) {
            return $data;
        }
        // 处理分页数据
        $data['page']['total'] = $res['total'];
        $data['page']['totalPage'] = $res['last_page'];

        // 处理数据
        foreach ($res['data'] as &$item) {
            $item['employeeId'] = $item['id'];
            $item['avatar'] = file_full_url($item['avatar']);
        }
        unset($item);
        $data['list'] = $res['data'];

        return $data;
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
        ];
    }

    /**
     * 无限递归查询.
     */
    private function recursion(int $id, array $ids): array
    {
        // 子部门信息
        $childDepartment = $this->workDepartmentService->getWorkDepartmentsByParentId($id, ['id']);
        if (count($childDepartment) > 0) {
            $childIds = array_column($childDepartment, 'id');
            $ids = array_merge($ids, $childIds);
        }
        // 处理子部门
        foreach ($childDepartment as &$v) {
            $ids = $this->recursion($v['id'], $ids);
        }
        unset($v);
        return $ids;
    }
}
